import React from 'react';
import { Form, Input, DatePicker, Card, Table, Progress } from 'antd';
import { history } from 'umi'
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { Pagination, AdvancedSearch, TableFilter } from '@/components';
import moment from 'moment';
import { DepartmentTree } from '../components';
import { useSubordinateExecuteTaskList } from '../../hooks';
import { TaskStatus, TaskStatusList, toNum } from '../../utils';
import styles from './Execute.less';

const { RangePicker } = DatePicker;

const Execute = ({ form, location }) => {
    const { getFieldDecorator, getFieldsValue } = form;
    const { query: urlQuery } = location;
    const [query, setQuery] = React.useState({
        companyCode: urlQuery.companyCode || '',
        departmentCode: urlQuery.departmentCode || '',
        taskName: urlQuery.taskName || '',
        executeEmployeeName: urlQuery.executeEmployeeName || '',
        planEndTimeStart: urlQuery.planEndTimeStart,
        planEndTimeEnd: urlQuery.planEndTimeEnd,
        orderByField: urlQuery.orderByField || '',
        pageNo: urlQuery.pageNo || 1,
        pageSize: urlQuery.pageSize || 10,
        taskStatus: toNum(urlQuery.taskStatus)
    });

    const [taskLoading, taskData, taskTotal] = useSubordinateExecuteTaskList(query); // 获取任务管理列表

    const routerReplace = newQuery => {
        // history.push({
        //     query: {
        //         ...urlQuery,
        //         ...newQuery
        //     }
        // });
        setQuery({
            ...query,
            ...newQuery
        });
    };

    // 分页操作
    const handlePaginationChange = _pagination => {
        const { current, ...rest } = _pagination;
        routerReplace({
            ...rest,
            pageNo: current
        });
    };

    const handleTableChange = async (pagination, filters, sorter) => {
        const { taskStatus = [] } = filters;
        let orderByField = '';
        if (sorter && sorter.field && sorter.order) {
            orderByField = `${sorter.field}|${sorter.order.replace('end', '')}`;
        }
        routerReplace({
            orderByField,
            taskStatus: taskStatus.length > 0 ? taskStatus[0] : '',
            pageNo: 1
        });
    };

    const defaultSort = type => {
        // const { orderByField = '' } = urlQuery;
        const { orderByField = '' } = query;
        const str = orderByField ? orderByField.replace(`${type}|`, '').trim() : '';
        if (str === 'asc') {
            return 'ascend';
        }
        if (str === 'desc') {
            return 'descend';
        }
        return false;
    };

    const renderEllipsis = text => (
        <div style={{ width: '100%', minWidth: 200, position: 'relative' }}>
            <span
                style={{
                    position: 'absolute',
                    left: 0,
                    right: 0,
                    top: 0,
                    transform: 'translateY(-50%)',
                    overflow: 'hidden',
                    whiteSpace: 'nowrap',
                    textOverflow: 'ellipsis'
                }}
                title={text}
            >
                {text}
            </span>
        </div>
    );

    const renderProgress = (text = '0', record) => {
        let format = {};
        let color = '#5AD8A6';
        if (toNum(text) >= 100) {
            format = {
                format: () => '100%'
            };
        }
        if (record.taskStatus === TaskStatus.FINISH || record.taskStatus === TaskStatus.CANCEL) {
            color = '#999999';
        } else if (record.taskStatus === TaskStatus.PAUSE) {
            color = '#FFA784';
        }
        return (
            <Progress
                className={styles.taskProgress}
                percent={Number(text)}
                strokeColor={color}
                size="small"
                {...format}
            />
        );
    };

    const columns = [
        {
            title: '执行人',
            dataIndex: 'taskExecutor',
            width: 120
        },
        {
            title: '任务名称',
            dataIndex: 'taskName',
            render: text => renderEllipsis(text)
        },
        {
            title: '截止时间',
            dataIndex: 'planEndTime',
            width: 120,
            sorter: () => {},
            sortOrder: defaultSort('planEndTime'),
            render: text => {
                if (text) {
                    return text.indexOf('23:59:59') !== -1
                        ? moment(text).format('MM-DD')
                        : moment(text).format('MM-DD HH:mm');
                }
                return '';
            }
        },
        {
            title: '状态',
            dataIndex: 'taskStatus',
            filters: TaskStatusList,
            width: 100,
            filteredValue: typeof query.taskStatus === 'number' ? [query.taskStatus] : [],
            filterMultiple: false,
            filterDropdown: filterProps => <TableFilter {...filterProps} />,
            render: text => (TaskStatusList[text - 1] ? TaskStatusList[text - 1].text : '')
        },
        {
            title: '当前进度',
            dataIndex: 'taskProgress',
            width: 150,
            render: (text, record) => renderProgress(text, record)
        }
    ];

    const getParams = () => {
        const param = getFieldsValue();
        const { deadLine = [], ...rest } = param;
        return {
            ...rest,
            planEndTimeStart: deadLine.length > 1 ? deadLine[0].format('YYYY-MM-DD 00:00:00') : '',
            planEndTimeEnd: deadLine.length > 1 ? deadLine[1].format('YYYY-MM-DD 23:59:59') : ''
        };
    };

    const handleSubmit = () => {
        routerReplace({
            ...getParams(),
            pageNo: 1
        });
    };

    const handelReset = () => {
        handleSubmit();
    };

    const handleSelect = item => {
        // console.log(item);
        const { organizationType, organizationCode } = item;
        form.setFieldsValue({
            taskName: '',
            executeEmployeeName: '',
            deadLine: []
        });
        routerReplace({
            companyCode: organizationType <= 2 ? organizationCode : '',
            departmentCode: organizationType === 3 ? organizationCode : '',
            taskName: '',
            executeEmployeeName: '',
            planEndTimeStart: '',
            planEndTimeEnd: '',
            orderByField: '',
            pageNo: 1,
            pageSize: 10,
            taskStatus: ''
        });
    };

    React.useEffect(() => {
        const { executeEmployeeName, taskName, planEndTimeStart, planEndTimeEnd } = query;
        form.setFieldsValue({
            executeEmployeeName: executeEmployeeName || '',
            taskName: taskName || '',
            deadLine: planEndTimeStart && planEndTimeEnd ? [moment(planEndTimeStart), moment(planEndTimeEnd)] : []
        });
    }, []);

    return (
        <PageHeaderWrapper>
            <Card bordered={false}>
                <div style={{ display: 'flex' }}>
                    <div style={{ width: 270, marginRight: 16 }}>
                        <DepartmentTree onSelect={handleSelect} />
                    </div>
                    <div style={{ flex: 1, overflow: 'hidden' }}>
                        <AdvancedSearch
                            form={form}
                            colConfig={{
                                xxl: 8,
                                xl: 12,
                                lg: 24,
                                md: 24,
                                sm: 24,
                                xs: 24
                            }}
                            onSubmit={handleSubmit}
                            onReset={handelReset}
                        >
                            <Form.Item label="任务名称">
                                {getFieldDecorator('taskName', {
                                    initialValue: ''
                                })(<Input placeholder="请输入任务名称" allowClear />)}
                            </Form.Item>
                            <Form.Item label="执行人">
                                {getFieldDecorator('executeEmployeeName', {
                                    initialValue: ''
                                })(<Input placeholder="请输入执行人" allowClear />)}
                            </Form.Item>
                            <Form.Item label="截止时间">
                                {getFieldDecorator('deadLine', {
                                    initialValue: []
                                })(
                                    <RangePicker
                                        dropdownClassName={styles.rangePicker}
                                        ranges={{
                                            本周: [moment().startOf('week'), moment().endOf('week')],
                                            本月: [moment().startOf('month'), moment().endOf('month')],
                                            本季度: [moment().startOf('quarter'), moment().endOf('quarter')]
                                        }}
                                    />
                                )}
                            </Form.Item>
                        </AdvancedSearch>
                        <Table
                            rowKey="id"
                            rowClassName={styles.tableRow}
                            bordered={false}
                            columns={columns}
                            loading={taskLoading}
                            dataSource={taskData}
                            onChange={handleTableChange}
                            pagination={false}
                            scroll={{ x: 'max-content' }}
                            onRow={record => ({
                                onClick: () => {
                                    history.push({
                                        pathname: '/work/task/taskdetail',
                                        query: { id: record.id || '' },
                                        state: { tabRoute: true, tabRefresh: true }
                                    });
                                }
                            })}
                        />
                        <Pagination
                            total={taskTotal}
                            current={Number(query.pageNo)}
                            pageSize={Number(query.pageSize)}
                            onChange={handlePaginationChange}
                            loading={taskLoading}
                        />
                    </div>
                </div>
            </Card>
        </PageHeaderWrapper>
    );
};

export default Form.create()(Execute);
